// CSE 142, Winter 2008, Marty Stepp // // This program demonstrates: // - breaking apart a number into its digits // - methods with while loops that compute and return values (digitSum) // - methods with while loops that return boolean values (hasAnOddDigit, allDigitsOdd) import java.util.*; // for Random public class Digits { public static void main(String[] args) { System.out.println("digit sum of 29107 = " + digitSum(29107)); System.out.println("digit sum of 1112 = " + digitSum(1112)); System.out.println("digit sum of 85 = " + digitSum(85)); System.out.println("digit sum of 0 = " + digitSum(0)); if (hasAnOddDigit(4822116)) { System.out.println("4822116 has an odd digit!"); } if (hasAnOddDigit(2448)) { System.out.println("4822116 has an odd digit!"); } if (allDigitsOdd(1353179)) { System.out.println("1353179 has all odd digits!"); } if (allDigitsOdd(9175293)) { System.out.println("9175293 has all odd digits!"); } if (allDigitsOdd(2468)) { System.out.println("2468 has all odd digits!"); } } // Returns the sum of the digits of the given number. // For example, digitSum(29107) returns 2+9+1+0+7 or 19. public static int digitSum(int number) { // 29107 int sum = 0; while (number > 0) { int lastDigit = number % 10; // 7 0 1 sum = sum + lastDigit; number = number / 10; // 2910 291 29 } return sum; } // Returns true if the given number has any digit whose value is an odd number, // and false if every digit of the number is even. public static boolean hasAnOddDigit(int number) { while (number > 0) { int lastDigit = number % 10; if (lastDigit % 2 == 1) { // this is an odd digit; number must have an odd digit now return true; } number = number / 10; } // if I get here, there were no odd digits return false; } // Returns true if every digit of the given number is an odd number. public static boolean allDigitsOdd(int number) { while (number > 0) { int lastDigit = number % 10; if (lastDigit % 2 == 0) { // this is an even digit; all digits can't be odd now return false; } number = number / 10; } // if I get here, there were no even digits return true; } }